import React from 'react'
import { SongList, SongItem } from './style'
import { getName } from '../../api/utils'
import { connect } from 'react-redux'
import {
  changePlayList,
  changeCurrentIndex,
  changeSequencePlayList
} from '../Player/store/actionCreator'

const mapDispatchtoProps = dispatch => {
  return {
    changePlayListDispatch(data) {
      dispatch(changePlayList(data))
    },
    changeCurrentIndexDispatch(data) {
      dispatch(changeCurrentIndex(data))
    },
    changeSequencePlayListDispatch(data) {
      dispatch(changeSequencePlayList(data))
    }
  }
}

const SongsList = React.forwardRef((props, refs) => {
  const { collectCount, showCollect, songs } = props
  const {
    changePlayListDispatch,
    changeCurrentIndexDispatch,
    changeSequecePlayListDispatch
  } = props
  const { musicAnimation } = props

  const totalCount = songs.length
  const selectItem = (e, index) => {
    changePlayListDispatch(songs)
    changeSequecePlayListDispatch(songs)
    changeCurrentIndexDispatch(index)
    musicAnimation(e.nativeEvent.clientX, e.nativeEvent.clientY)
    console.log(1)
  }
  const songList = list => {
    const res = list.map(item => {
      return (
        <li key={item.id} onClick={e => selectItem}>
          <span className="index"></span>
          <div className="info">
            <span>{item.name}</span>
            <span>
              {item.ar ? getName(item.ar) : getName(item.artists)} -{' '}
              {item.al ? item.al.name : item.album.name}
            </span>
          </div>
        </li>
      )
    })

    return res
  }

  const collect = count => {
    return (
      <div className="add_list">
        <i className="iconfont">&#xe613;</i>
        <span>收藏({Math.floor(count / 1000) / 10} 万)</span>
      </div>
    )
  }

  return (
    <SongList ref={refs} showBackground={props.showBackground}>
      <div className="first_line">
        <div className="play_all" onClick={e => selectItem(e, 0)}>
          <i className="iconfont">&#xe640;</i>
          <span>
            播放全部<span className="sum">(共{totalCount}首)</span>
          </span>
        </div>
        {showCollect ? collect(collectCount) : null}
      </div>
      <SongItem>{songList(songs)}</SongItem>
    </SongList>
  )
})

export default connect(null, mapDispatchtoProps)(React.memo(SongsList))
